package com.wolf.api;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

import com.wolf.javabean.API;
import com.wolf.javabean.API.ApiDatas;
import com.wolf.javabean.API.Apis;

public class ApiClient implements Runnable{

	public static String apiIp;
	public static int apiPort;
	public static Channel apiChannel;
	
	public static void runs() {
		new Thread(new ApiClient()).start();
	}
	
	public static BlockingQueue<ApiDatas.Builder> queue = new ArrayBlockingQueue<ApiDatas.Builder>(10);
	
	public void init(){
		Bootstrap boot = new Bootstrap();
		NioEventLoopGroup group = new NioEventLoopGroup(2);
		try {
			boot.group(group)
			.channel(NioSocketChannel.class)
			.handler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					// TODO Auto-generated method stub
					ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
					ch.pipeline().addLast(new ProtobufDecoder(API.ApiDatas.getDefaultInstance()));
					ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
					ch.pipeline().addLast(new ProtobufEncoder());
				}
				
			});
			apiChannel = boot.connect(apiIp,apiPort).sync().channel();
			System.out.println("启动到Api服务的连接:"+apiIp+apiPort);
			apiChannel.writeAndFlush(queue.take());
			System.out.println("api数据已发送");
			//apiChannel.closeFuture().sync();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		init();
	}
	
}
